var fs = require('fs');
var data = '';

// 可读流
var readerStream = fs.createReadStream('input.txt');
// 可写流
var writerStream = fs.createWriteStream('output1.txt');
readerStream.setEncoding('UTF8');

// 处理流的事件:data end error
readerStream.on('data', function(chunk) {
  console.log('data=============');
  console.log(chunk);
  data += chunk;
});

readerStream.on('end', function() {
  console.log('end==============');
  console.log(data);
  writerStream.write(data, 'UTF8');
  writerStream.end();
});

readerStream.on('error', function(err) {
  console.log(err.stack);
});

// 处理流事件 --> data, end, and error
writerStream.on('finish', function() {
  console.log("写入完成。");
});

writerStream.on('error', function(err) {
  console.log(err.stack);
});

console.log("程序执行完毕");

// pipe 如果没有定时任务，则会输出两次input文件到output2文件下
setTimeout(function() {
  // 可读流
  var readerStream = fs.createReadStream('input.txt');
  // 可写流
  var writerStream = fs.createWriteStream('output2.txt');
  readerStream.pipe(writerStream);
}, 5000);
